package com.yunsuo.service;




import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.File;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class ImageDemo {
    

    public static int getImage(String Lid,String Iuuid){
        //调用代码拍照,没有摄像头，先省略
        InputStreamReader stdISR = null;
        InputStreamReader errISR = null;
        Process process = null;
        //System.out.println("Iuuid======="+Iuuid);
        String command =
                "raspistill -o /home/pi/Pictures/"
                        +Lid+"_"+Iuuid+".jpg";
        //System.out.println("拍照片代码运行");
        try {
            process = Runtime.getRuntime().exec(command);
            int exitValue = process.waitFor();


            String line = null;

            stdISR = new InputStreamReader(process.getInputStream());
            BufferedReader stdBR = new BufferedReader(stdISR);
            while ((line = stdBR.readLine()) != null) {
                //System.out.println("STD line:" + line);
            }

            errISR = new InputStreamReader(process.getErrorStream());
            BufferedReader errBR = new BufferedReader(errISR);
            while ((line = errBR.readLine()) != null) {
                //System.out.println("ERR line:" + line);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                if (stdISR != null) {
                    stdISR.close();
                }
                if (errISR != null) {
                    errISR.close();
                }
                if (process != null) {
                        process.destroy();
                }
            } catch (IOException e) {
                //System.out.println("正式执行命令：" + command + "有IO异常");
            }
        }
        //图片文件名 Lid_uuid.jpg
//        postXml("/home/pi/DoorImages/7_qwerqwer.jpg",
//                "http://localhost:8080/lockV1_1_war_exploded/raspberry/upload");

        String path="/home/pi/Pictures/"+Lid+"_"+Iuuid+".jpg";
        //postXml("/Users/leo/Pictures/6_ddddd.jpg","http://localhost:8080/lockV1_1_war_exploded/raspberry/upload");
        uploadFileByHttpPost(new File(path),"http://192.168.43.203:8081/raspberry/upload");
        //uploadFileByHttpPost(new File(path),"http://10.0.2.2:8080/lockV1_1_war/raspberry/upload");


        //final HttpConnectionImage httpConnection = new HttpConnectionImage();
        Map<String, String> params = new HashMap<String, String>();
        //查到数据，返回user用户数据，以json的形式
        params.put("result", "ok");
        //params.put("method","getImage");
        params.put("Lid",Lid);
        params.put("Iuuid",Iuuid);
        //String result = httpConnection.connection(params);
        //GenerateImage(strImg);
        return 0;
    }

//    //图片转化成base64字符串
//    public static String GetImageStr() {//将图片文件转化为字节数组字符串，并对其进行Base64编码处理
//        String imgFile = "/home/pi/DoorImages/a.jpg";//待处理的图片
//        InputStream in = null;
//        byte[] data = null;
//        //读取图片字节数组
//        try {
//            in = new FileInputStream(imgFile);
//            data = new byte[in.available()];
//            in.read(data);
//            in.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        //对字节数组Base64编码
//        BASE64Encoder encoder = new BASE64Encoder();
//        return encoder.encode(data);//返回Base64编码过的字节数组字符串
//    }

//    //base64字符串转化成图片
//    public static boolean GenerateImage(String imgStr) {   //对字节数组字符串进行Base64解码并生成图片
//        if (imgStr == null) //图像数据为空
//            return false;
//        BASE64Decoder decoder = new BASE64Decoder();
//        try {
//            //Base64解码
//            byte[] b = decoder.decodeBuffer(imgStr);
//            for (int i = 0; i < b.length; ++i) {
//                if (b[i] < 0) {//调整异常数据
//                    b[i] += 256;
//                }
//            }
//            //生成jpeg图片
//            String imgFilePath = "/Users/leo/IdeaProjects/respberryLock/b.jpg";//新生成的图片
//            OutputStream out = new FileOutputStream(imgFilePath);
//            out.write(b);
//            out.flush();
//            out.close();
//            return true;
//        } catch (Exception e) {
//            return false;
//        }
//    }


    /**
     * @param file
     * @param url
     */
    public static void uploadFileByHttpPost(File file, String url) {
        CloseableHttpClient client = HttpClients.custom().build();
        try {
            HttpPost post = new HttpPost(url);
            FileBody fileBody = new FileBody(file);
            /*
             * 可以在MultipartEntityBuilder中添加多个part（ContentBody），用来传递多个参数
             * ByteArrayBody
             * InputStreamBody
             * FileBody
             * StringBody
             */
            HttpEntity entity = MultipartEntityBuilder.create().addPart("file", fileBody).build();
            post.setEntity(entity);
            CloseableHttpResponse resp = client.execute(post);
            int status = resp.getStatusLine().getStatusCode();
            if (status == 200) {
                //Logger.getLogger(HttpClientUtil.class).info("上传成功");
            } else {
                //Logger.getLogger(HttpClientUtil.class).info("上传失败");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

//    public static int postXml(String path,String url){
//        DefaultHttpClient client = new DefaultHttpClient();
//        HttpPost post = new HttpPost(url);
//        MultipartEntity multipartEntity = new MultipartEntity();
//        FileBody cbFileBody = new FileBody(new File(path));
//        multipartEntity.addPart("file", cbFileBody);
//        post.setEntity(multipartEntity);
//        int  statusCode = -1;
//        try {
//            HttpResponse response = client.execute(post);
//            statusCode = response.getStatusLine().getStatusCode();
//        } catch (Throwable e) {
//            //记录异常日志
//            //SolrErrorCategory.error("xml文件post到solr服务器："+url+" 创建索引出现异常错误！异常信息："+e.getMessage(),e);
//        }
//        return statusCode;
//    }
}
